﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using Web.CrmContacto.Code;
using Web.Framework;
using CrmContacto.WebApp.Code.InnerClasses;
using CrmContacto.Contracts.Contracts.Misc;
using CrmContacto.Contracts.Contracts;
using Web.Framework.Translate;
using CrmContacto.Contracts.Contracts.Search;
using Web.CrmContacto.Code.Security;
using Web.Framework.Helpers;

namespace CrmContacto.WebApp.App
{
    public partial class AccionDeMarketingEmailResultadosEdit : BasePage
    {
        public string Pais
        {
            get
            {
                return ConfigurationManager.AppSettings["LenguajePorDefecto"];
            }
        }

        public int accionDeMarketingId
        {
            get
            {
                return Convert.ToInt32(ViewState["accionDeMarketingId"]);
            }
            set
            {
                ViewState["accionDeMarketingId"] = value;
            }
        }

        private List<LinkButton> actionButtons = new List<LinkButton>();
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            LinkButton volverButton = new LinkButton();
            volverButton.ID = "BosActionMenuVolver";
            volverButton.CausesValidation = false;
            volverButton.Text = LocalizationProvider.Instance["Bo.Command.Volver"];
            volverButton.Click += new EventHandler(lnkCancelar_Click);

            actionButtons.Add(volverButton);
            base.LoadContextActions(actionButtons);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                HasPermissionToSeeMe(CrmSecurity.MARKETINGACTION_ADD_EMAILRESULTS);
                lnkVerResultados.Attributes.Add("aspnetid", lnkVerResultados.ClientID);

                if (!IsPostBack)
                {
                    accionDeMarketingId = Convert.ToInt32(this.Request["accionDeMarketingId"]);

                    AccionDeMarketingSearch serach = new AccionDeMarketingSearch();
                    serach.Id = accionDeMarketingId;
                    var accionDeMarketing = WebServiceHelper.GetAccionesDeMarketing(serach).First();
                    lblAccionDeMarketing.Text = accionDeMarketing.Nombre;

                    LoadResultados();
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void LoadResultados()
        {

            List<AccionDeMarketingEmailResultado> resultadoList = HttpContext.Current.Cache.Get(HttpContext.Current.Session.SessionID + MiscClass.EmailMarketingImportRecordsKey) as List<AccionDeMarketingEmailResultado>;
            if (resultadoList != null)
            {
                this.Grid.DataSource = resultadoList;
                this.Grid.DataBind();

                pnlCustomers.Visible = true;
                lnkCancelar.Visible = true;

                // una vez que los muestro ya no los quiero en sessión
               // Session[MiscClass.EmailMarketingImportRecordsKey] = null;
            }
        }

        public void Volver()
        {            
            Response.Redirect(Request.Url.Scheme + "://" + Request.Url.Authority + MiscClass.UrlAccionDeMarketingSwap + string.Format("?Id={0}", accionDeMarketingId), true);            
        }

        protected override void ApplySecurity()
        {
            base.ApplySecurity();

            //this.btnAgregarNuevo.Visible = HasPermissionFor(PlanProdSecurity.DESTINO_CREAR);

            //if (this.GridCategorias.DataSource != null)
            //{
            //    this.GridCategorias.Columns[0].Visible = HasPermissionFor(PlanProdSecurity.DESTINO_EDITAR);
            //    this.GridCategorias.Columns[1].Visible = HasPermissionFor(PlanProdSecurity.DESTINO_ELIMINAR);
            //}
        }

        private int colTipoRebote = 1;

        protected void Grid_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    AccionDeMarketingEmailResultado resultado = (AccionDeMarketingEmailResultado)e.Row.DataItem;

                    var cellRebote = e.Row.Cells[colTipoRebote];

                    if (!resultado.EmailTipoRebote.HasValue)
                    {
                        cellRebote.Text = string.Empty;
                    }
                    else
                    {
                        cellRebote.Text = resultado.EmailTipoRebote.Value ? LocalizationProvider.Instance["EstadoEmail.ReboteHard"] : LocalizationProvider.Instance["EstadoEmail.ReboteSoft"];
                    }                   
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void Grid_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                //if (e.CommandName == "editar")
                //{
                //    int contactoId = Convert.ToInt32(this.Grid.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
                //    this.Response.Redirect(string.Format(Request.Url.Scheme + "://" + Request.Url.Authority + MiscClass.UrlCustomerEdit + "?Id={0}", contactoId), true);
                //}
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }


        protected void lnkCancelar_Click(object sender, EventArgs e)
        {
            try
            {
                Volver();
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void lnkIrAAccion_Click(object sender, EventArgs e)
        {
            try
            {
                this.NavigationContext.RedirectTo(MiscClass.UrlAccionDeMarketingSwap, string.Format("?Id={0}", accionDeMarketingId));
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }      
               
        protected void lnkVerResultados_Click(object sender, EventArgs e)
        {
            try
            {
                LoadResultados();
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void lnkExportarAExcel_Click(object sender, EventArgs e)
        {
            try
            {
                bool previousAllowPaging = this.Grid.AllowPaging;
                this.Grid.AllowPaging = false;

                LoadResultados();

                GridViewExportExcelUtil.Export("ResultadosEmail.xls", this.Grid);

                this.Grid.AllowPaging = previousAllowPaging;
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }
    }
}